package com.robot.botrunning.utils;

import com.robot.botrunning.pojo.Robot;

import java.util.LinkedList;
import java.util.Queue;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

public class runningPool extends Thread{//线程一加入到pool，线程二取出并执行代码

    private final static ReentrantLock lock = new ReentrantLock();
    private final Condition condition = lock.newCondition();
    private Queue<Robot> robots = new LinkedList<>();

    public void  addRobot(Robot robot){//加入执行池
        lock.lock();//对消息队列加锁

        try {
            robots.add(robot);
            System.out.println("加入bot");
            condition.signalAll();//唤醒所有线程
        }finally {
            lock.unlock();
        }
    }
    private void running(Robot robot){//执行代码
        runningCode runningCode = new runningCode();
        runningCode.startTimeOut(2000,robot);
    }
    @Override
    public void run() {//理发师问题,消息队列
        while (true){
            lock.lock();
            if(robots.isEmpty()){
                try {
                    condition.await();//队列中为空,阻塞线程
                } catch (InterruptedException e) {
                    lock.unlock();
                    throw new RuntimeException(e);
                }
            }else{
                Robot robot = robots.remove();
                lock.unlock();
                running(robot);
            }
        }
    }
}
